<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户信息管理</span>
        <div class="extra">
          <!-- <el-button type="primary" @click="add">新增用户</el-button> -->
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="姓名：">
        <el-input v-model="user.name" placeholder="请输入姓名" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="角色：" style="width: 300px">
        <el-select v-model="user.role" placeholder="请选择角色">
          <el-option label="机构管理员" value="机构管理员"></el-option>
          <el-option label="发布人员" value="发布人员"></el-option>
          <el-option label="审核人员" value="审核人员"></el-option>
          <el-option label="学员" value="学员"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="账号状态：" style="width: 700px">
        <el-select v-model="user.status" placeholder="请输入状态">
          <el-option label="正常" value="正常"></el-option>
          <el-option label="注册未审核" value="注册未审核"></el-option>
        </el-select>
        <el-button type="primary" @click="show" style="margin-left: 15px;">查询</el-button>
        <el-button @click="clear">重置</el-button>
        <el-button type="primary" @click="exportData">导出</el-button>
        <el-button type="primary" @click="importData">导入</el-button>
      </el-form-item>

    </el-form>

    <el-table ref="multipleTable" @selection-change="handleSelectionChange" :data="tableData" style=" width: 100%;">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="编号" header-align="center" align="center" width="80px"></el-table-column>
      <el-table-column prop="name" label="姓名" header-align="center" align="center"></el-table-column>
      <el-table-column prop="password" label="密码" header-align="center" align="center"></el-table-column>
      <el-table-column prop="role" label="角色" header-align="center" align="center"></el-table-column>
      <el-table-column prop="agencyId" label="归属机构" header-align="center" align="center">
        <template slot-scope="scope">
          {{ getAgencyName(scope.row.agencyId) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="账号状态" header-align="center" align="center"></el-table-column>
      <el-table-column label="操作" width="125" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button v-show="scope.row.status === '正常'" class="el-icon-edit" type="primary" circle plain
            @click="updateInfo(scope.row.id)">
          </el-button>
          <el-button v-show="scope.row.status === '注册未审核'" class="el-icon-view" type="danger" circle plain
            @click="updateInfo(scope.row.id)">
          </el-button>
          <el-button class="el-icon-delete" type="danger" circle plain @click="deleteById(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <el-pagination style="margin-top: 20px;text-align: right;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :background="background" :current-page="currentPage" :page-sizes="[5, 10]"
      :page-size="5" layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>

    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="close" width="30%">
      <el-form :model="user">
        <el-form-item label="姓名" :label-width="formLabelWidth" :rules="[{ required: true }]">
          <el-input v-model="user.name" placeholder="请输入姓名" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" :rules="[{ required: true }]">
          <el-input v-model="user.password" placeholder="请输入密码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone" :rules="[
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }, { required: true }
        ]">
          <el-input v-model="user.phone" placeholder="请输入手机号" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="证件号" :label-width="formLabelWidth" prop="idNumber" :rules="[
          { pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/, message: '证件号格式错误', trigger: 'blur' }
          , { required: true }]">
          <el-input v-model="user.idNumber" placeholder="请输入证件号" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属机构" :label-width="formLabelWidth" v-show="user.agencyId !== 0"
          :rules="[{ required: true }]">
          <el-select v-model="user.agencyId" placeholder="请选择" style="width:100%">
            <el-option v-for="item in agencyList" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型" :label-width="formLabelWidth" :rules="[{ required: true }]">
          <el-select v-model="user.role" placeholder="请选择类型" style="width:100%">
            <el-option label="机构管理员" value="机构管理员"></el-option>
            <el-option label="发布人员" value="发布人员"></el-option>
            <el-option label="审核人员" value="审核人员"></el-option>
            <el-option label="学员" value="学员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false; clear()">取消</el-button>
        <el-button v-show="user.status === '正常'" type="primary" @click="addForm()">确定</el-button>
        <el-button v-show="user.status === '注册未审核'" type="primary" @click="addForm()">确定</el-button>
      </div>
    </el-dialog>

  </el-card>





  <!--分页工具条-->



</template>
<script>


import { addUser, addUsers, changeUser, deleteUser, getAllUsers } from "@/api/user";
import { getAgencyList } from "@/api/agency";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      user: { "password": "123456" },
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      agencyList: [],
      formLabelWidth: "80px",
      theMajorOfMy: "",
      loading: false,
    }
  },
  methods: {
    validateAge(rule, value, callback) {
      if (value === undefined || value === null || value === '') {
        return callback(new Error('请输入年龄'));
      }
      if (value < 0 || value > 100) {
        callback(new Error('年龄必须在0到100之间'));
      } else {
        callback();
      }
    },
    show() {

      getAllUsers(this.user, this.currentPage, this.pageSize).then((res) => {
        //console.log(res)
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show()
          }
          //console.log(this.tableData)
        }
      }).catch((e) => {
      })
    },
    clear() {
      this.user = {};
      this.show();
    },
    add() {
      this.user = {};
      this.user.password = "123456";
      this.addOrUpdate = true;
      this.dialogVisible = true;
      this.title = "新增用户";
    },
    addForm() {

      if (this.addOrUpdate) {
        addUser(this.user).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        changeUser(this.user).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.user.status = "正常";
            this.show();
          }
        }).catch(e => {
        });
      }

    },

    close() {
      this.dialogVisible = false;
      this.user = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.user = this.tableData.filter(data => data.id == id)[0];
      this.dialogVisible = true;
      this.title = "编辑用户";
    },
    deleteById(id) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(this.tableData.filter(data => data.id === id)[0]);
      this.deleteByIds()
    },
    deleteByIds() {

      // 弹出确认提示框
      this.$confirm("你确认删除该条信息吗？", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //用户点击确认按钮
        //1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id;
        }
        //console.log(this.selectedIds);
        //2. 发送AJAX请求
        deleteUser(this.selectedIds).then((resp) => {
          if (resp.data.code === 1) {
            //删除成功
            this.$message.success("删除成功");
            this.show();
          } else {
            this.$message.error(resp.data.msg);
          }
        }).catch(() => {
        });

      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("取消删除");
      });

    },
    getAllAgencyList() {
      getAgencyList().then((res) => {
        if (res.data.code === 1) {
          this.agencyList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getAgencyName(id) {
      if (id === 0) {
        return "超级管理员";
      }
      let agency = this.agencyList.find(data => data.id === id);
      return agency ? agency.name : "";
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },


    //导出
    async exportData() {
      this.loading = true;
      this.currentPage = 1;
      this.pageSize = this.totalCount;

      try {
        await getAllUsers(this.user, this.currentPage, this.pageSize).then((res) => {
          if (res.data.code === 1) {
            //将learningSituationList拆开放入属性中
            const data = this.tableData;

            // 创建工作簿对象
            const wb = XLSX.utils.book_new();

            // 将数据添加到工作簿中，假设 data 是一个二维数组或对象数组
            // 如果 data 是对象数组，使用 XLSX.utils.json_to_sheet(data)
            // 如果 data 是二维数组，使用 XLSX.utils.aoa_to_sheet(data)
            const ws = XLSX.utils.json_to_sheet(data);

            // 将工作表添加到工作簿中
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            // 写入工作簿，生成 XLSX 文件
            const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
            // 使用 FileSaver 保存文件
            try {
              FileSaver.saveAs(
                new Blob([wbout], { type: "application/octet-stream" }),
                this.getAgencyName(this.tableData[0].agencyId) + "_机构账号信息.xlsx"
              );
            } catch (e) {
              console.error(e);
            }


          }
        }).catch((e) => {
        })
      } finally {
        this.currentPage = 1;
        this.pageSize = 5;
        this.show();
        this.loading = false;
      }
    },

    async importData() {
      // 创建一个文件输入元素
      const inputElement = document.createElement('input');
      inputElement.type = 'file';
      inputElement.accept = '.xlsx, .xls'; // 接受的文件类型
      // 当文件被选中时触发读取操作
      inputElement.addEventListener('change', async (event) => {
        const file = event.target.files[0];
        if (!file) {
          return;
        }
        try {
          // 读取文件
          const data = await this.readFile(file);
          // 使用 XLSX 解析文件
          const workbook = XLSX.read(data, { type: 'array' });
          // 获取第一个工作表
          const worksheet = workbook.Sheets[workbook.SheetNames[0]];
          // 将工作表转换为 JSON
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
          // 处理导入的数据
          this.processImportedData(jsonData);
        } catch (e) {
          console.error(e);
        }
      });
      // 触发文件选择
      inputElement.click();
    },

    // 读取文件为 ArrayBuffer
    readFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
      });
    },

    // 处理导入的数据
    processImportedData(data) {
      // 根据你的需求处理导入的数据
      console.log(data);
      // 例如，你可以将数据添加到你的应用状态中，或者更新数据库等
      const headers = data[0]; // 第一行是列标题
      const dataObjects = data.slice(1).map(row => { // 从第二行开始是数据
        const obj = {};
        headers.forEach((header, index) => {
          obj[header] = row[index] === undefined ? null : row[index];
        });
        return obj;
      });
      addUsers(dataObjects).then((res) => {
        if (res.data.code === 1) {
          this.$message.success("添加成功");
        }
      }).catch((e) => { })

    },

  },
  mounted() {
    this.show();
    this.getAllAgencyList();
  },
};
</script>


<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}


.basic-info-container {
  display: flex; // 使用flex布局
  flex-wrap: wrap; // 允许元素换行
  margin-right: -10px; // 调整外边距以对齐
}

.basic-info-border,
.basic-info-border2 {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  position: relative;
  padding-top: 30px;
  margin-bottom: 20px; // 添加底部外边距
  width: 100%; // 设置宽度为100%，或者您可以设置一个固定的宽度
  box-sizing: border-box; // 确保padding和border包含在宽度内
}

.basic-info-border::before,
.basic-info-border2::before {
  content: "";
  position: absolute;
  top: -15px;
  left: 10px;
  background-color: #409EFF;
  color: white;
  padding: 5px;
  border-radius: 3px;
  font-weight: bold;
}

.basic-info-border::before {
  content: "基本信息";
}

.basic-info-border2::before {
  content: "客户关键人物信息";
}

// 如果需要，可以为两个框设置最大宽度
.max-width-box {
  max-width: 900px; // 或者您希望的任何宽度
}
</style>
<script setup>
</script>
